package web

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
)

// QueryTestPaper 查询试卷
func QueryTestPaper(c *gin.Context) {
	DB := common.GetDB()
	name := c.PostForm("name")
	pageSize, _ := strconv.Atoi(c.PostForm("pageSize"))
	pageIndex, _ := strconv.Atoi(c.PostForm("pageIndex"))

	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageIndex <= 0 {
		pageIndex = 1
	}
	//var testPaper model.TestPaper
	testPaper := make([]model.TestPaper, 0)
	var total int
	if name != "" {
		DB.Where("name LIKE ?", "%"+name+"%").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&testPaper).Offset(-1).Limit(-1).Count(&total)
		response.Reponse(c, http.StatusOK, 200, gin.H{
			"data":     testPaper,
			"total":    total,
			"page":     pageIndex,
			"pageSize": pageSize,
		}, "获取成功")
		return
	} else {
		DB.Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&testPaper).Offset(-1).Limit(-1).Count(&total)
		response.Reponse(c, http.StatusOK, 200, gin.H{
			"data":     testPaper,
			"total":    total,
			"page":     pageIndex,
			"pageSize": pageSize,
		}, "获取成功")
		return
	}
}
